"""
管理后台 - 城市管理员管理接口
"""
from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import Optional, List
from pydantic import BaseModel
from datetime import datetime

from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.core.permissions import require_permission, Permission
from app.models.user import User
from app.models.city_manager import CityManager, CityManagerStatus
from app.schemas.common import ApiResponse
from app.utils.helpers import generate_id
from loguru import logger

router = APIRouter(prefix="/city-manager", tags=["管理后台-城市管理员"])


class CityManagerListResponse(BaseModel):
    """城市管理员列表响应"""
    list: List[dict]
    total: int
    page: int
    pageSize: int


class CityManagerApproveRequest(BaseModel):
    """审核城市管理员请求"""
    action: str  # approve, reject
    monthlySalary: Optional[float] = None
    rejectReason: Optional[str] = None


@router.get("/list", response_model=ApiResponse[CityManagerListResponse])
@require_permission(Permission.CITY_MANAGER_VIEW)
async def get_city_manager_list(
    page: int = Query(1, ge=1),
    pageSize: int = Query(20, ge=1, le=100),
    keyword: Optional[str] = Query(None),
    city: Optional[str] = Query(None),
    status: Optional[str] = Query(None),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取城市管理员列表"""
    logger.info(f"📋 获取城市管理员列表: page={page}")
    
    # 基础查询
    query = db.query(CityManager)
    
    # 关键词搜索（搜索用户信息）
    if keyword:
        # 先查询匹配的用户
        users = db.query(User).filter(
            or_(
                User.nick_name.like(f"%{keyword}%"),
                User.phone.like(f"%{keyword}%")
            )
        ).all()
        user_ids = [u.id for u in users]
        if user_ids:
            query = query.filter(CityManager.user_id.in_(user_ids))
        else:
            # 如果没有匹配的用户，返回空列表
            return ApiResponse(data={
                "list": [],
                "total": 0,
                "page": page,
                "pageSize": pageSize
            })
    
    # 城市筛选
    if city:
        query = query.filter(
            or_(CityManager.city_name == city, CityManager.city_id == city)
        )
    
    # 状态筛选
    if status:
        query = query.filter(CityManager.status == status)
    
    # 总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * pageSize
    managers = query.order_by(CityManager.created_at.desc()).offset(offset).limit(pageSize).all()
    
    # 转换为字典并关联用户信息
    manager_list = []
    for manager in managers:
        manager_dict = manager.to_dict()
        # 获取用户信息
        user = db.query(User).filter(User.id == manager.user_id).first()
        if user:
            manager_dict['userName'] = user.nick_name
            manager_dict['userPhone'] = user.phone
            manager_dict['userAvatar'] = user.avatar
        manager_list.append(manager_dict)
    
    logger.success(f"✅ 返回城市管理员列表: total={total}, count={len(manager_list)}")
    
    return ApiResponse(data={
        "list": manager_list,
        "total": total,
        "page": page,
        "pageSize": pageSize
    })


@router.get("/applications", response_model=ApiResponse[List[dict]])
@require_permission(Permission.CITY_MANAGER_MANAGE)
async def get_applications(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取待审核申请列表"""
    logger.info("📋 获取待审核申请")
    
    # 查询待审核的申请
    applications = db.query(CityManager).filter(
        CityManager.status == CityManagerStatus.PENDING
    ).order_by(CityManager.applied_at.desc()).all()
    
    # 转换为字典并关联用户信息
    app_list = []
    for app in applications:
        app_dict = app.to_dict()
        user = db.query(User).filter(User.id == app.user_id).first()
        if user:
            app_dict['userName'] = user.nick_name
            app_dict['userPhone'] = user.phone
            app_dict['userAvatar'] = user.avatar
        app_list.append(app_dict)
    
    logger.success(f"✅ 返回待审核申请: count={len(app_list)}")
    
    return ApiResponse(data=app_list)


@router.post("/{manager_id}/review", response_model=ApiResponse[str])
@require_permission(Permission.CITY_MANAGER_MANAGE)
async def review_application(
    manager_id: str,
    request: CityManagerApproveRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """审核城市管理员申请"""
    logger.info(f"✅ 审核城市管理员: {manager_id}, action: {request.action}")
    
    manager = db.query(CityManager).filter(CityManager.id == manager_id).first()
    if not manager:
        raise HTTPException(404, "申请不存在")
    
    if request.action == 'approve':
        manager.status = CityManagerStatus.APPROVED
        manager.monthly_salary = request.monthlySalary or 0
        manager.approved_at = datetime.now()
        manager.approved_by = current_user.id
        
        # 更新用户角色
        user = db.query(User).filter(User.id == manager.user_id).first()
        if user:
            user.role = 'city_manager'
            user.city_id = manager.city_id
            user.city_name = manager.city_name
        
        message = "审核通过"
        
    elif request.action == 'reject':
        manager.status = CityManagerStatus.REJECTED
        manager.reject_reason = request.rejectReason
        message = "审核拒绝"
    else:
        raise HTTPException(400, "无效的审核操作")
    
    db.commit()
    
    logger.success(f"✅ 城市管理员审核成功: {manager_id}, action: {request.action}")
    
    # TODO: 发送通知给申请人
    
    return ApiResponse(message=message)


@router.get("/{manager_id}", response_model=ApiResponse[dict])
@require_permission(Permission.CITY_MANAGER_VIEW)
async def get_city_manager_detail(
    manager_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取城市管理员详情"""
    manager = db.query(CityManager).filter(CityManager.id == manager_id).first()
    if not manager:
        raise HTTPException(404, "城市管理员不存在")
    
    manager_dict = manager.to_dict()
    
    # 获取用户信息
    user = db.query(User).filter(User.id == manager.user_id).first()
    if user:
        manager_dict['userName'] = user.nick_name
        manager_dict['userPhone'] = user.phone
        manager_dict['userAvatar'] = user.avatar
    
    return ApiResponse(data=manager_dict)


class UpdateSalaryRequest(BaseModel):
    """更新补贴请求"""
    monthlySalary: float


@router.put("/{manager_id}/salary", response_model=ApiResponse[str])
@require_permission(Permission.CITY_MANAGER_MANAGE)
async def update_salary(
    manager_id: str,
    request: UpdateSalaryRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新月度补贴"""
    manager = db.query(CityManager).filter(CityManager.id == manager_id).first()
    if not manager:
        raise HTTPException(404, "城市管理员不存在")
    
    manager.monthly_salary = request.monthlySalary
    db.commit()
    
    return ApiResponse(message="补贴更新成功")


@router.post("/{manager_id}/suspend", response_model=ApiResponse[str])
@require_permission(Permission.CITY_MANAGER_MANAGE)
async def suspend_manager(
    manager_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """暂停城市管理员"""
    manager = db.query(CityManager).filter(CityManager.id == manager_id).first()
    if not manager:
        raise HTTPException(404, "城市管理员不存在")
    
    manager.status = CityManagerStatus.SUSPENDED
    
    # 更新用户角色
    user = db.query(User).filter(User.id == manager.user_id).first()
    if user:
        user.role = 'user'
    
    db.commit()
    
    return ApiResponse(message="已暂停")


@router.post("/{manager_id}/resume", response_model=ApiResponse[str])
@require_permission(Permission.CITY_MANAGER_MANAGE)
async def resume_manager(
    manager_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """恢复城市管理员"""
    manager = db.query(CityManager).filter(CityManager.id == manager_id).first()
    if not manager:
        raise HTTPException(404, "城市管理员不存在")
    
    manager.status = CityManagerStatus.APPROVED
    
    # 更新用户角色
    user = db.query(User).filter(User.id == manager.user_id).first()
    if user:
        user.role = 'city_manager'
    
    db.commit()
    
    return ApiResponse(message="已恢复")

